#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Author : fanzf
# @Version：V 0.1
# @File : __init__.py.py
# @desc :
import json
import sys
import traceback
from datetime import datetime
import os
import logging
from flask import Flask

from app.invokeEXE import login_web
from app.utils import loginMaiZuo, mao_yan_Flask, loginMaoYan, parse_maizuo_cookie, \
    parse_maoyan_cookie

BASEDIR = os.path.abspath(os.path.dirname(__file__))


def create_app():
    init_dir_log_message = []
    project_dir = init_dir(init_dir_log_message)
    logger = setup_logging(project_dir)
    logger.debug(init_dir_log_message)
    logger.debug("开始初始化 flask")
    app = Flask(__name__)
    # 初始化日志
    init_logger(app, logger)
    app.config["project_dir"] = project_dir
    # 延迟导入蓝图
    from .routes import bp
    app.register_blueprint(bp, url_prefix='/')
    logger.debug("初始化 flask--完成")
    return app


def init_logger(app, logger):
    app.logger = logger


# 配置日志
def setup_logging(project_dir):
    # 获取当前日期和时间
    now = datetime.now()
    # 格式化为 "yyyymmddhhmmss" 格式
    current_date_str = now.strftime("%Y%m%d%H%M%S")
    my_logger = logging.getLogger('my_logger')
    my_logger.setLevel(logging.DEBUG)
    log_path = os.path.join(project_dir, "logs")
    os.makedirs(log_path, exist_ok=True)
    fileName = 'crawl_log_' + current_date_str + '.log'
    log_path_new = os.path.join(log_path, fileName)
    # 创建一个文件处理器，并设置级别为DEBUG
    fh = logging.FileHandler(log_path_new, encoding='utf-8')
    fh.setLevel(logging.DEBUG)
    # 创建一个流处理器（控制台输出）
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    # 定义日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s -  %(threadName)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # 将文件处理器和流处理器添加到日志记录器
    my_logger.addHandler(fh)
    my_logger.addHandler(ch)
    return my_logger


def init_dir(logger):
    try:
        # 判断程序是不是用 PyInstaller 打包的
        current_directory = os.getcwd()
        logger.append("当前目录是:{}".format(current_directory) + "\n")

        # 判断程序是不是用 PyInstaller 打包的
        if getattr(sys, 'frozen', False):
            # 如果是，使用这个路径
            project_path = current_directory
        else:
            # 如果不是，使用普通的Python环境路径
            current_directory = os.path.dirname(os.path.abspath(__file__))
            project_path = os.path.dirname(current_directory)
        logger.append("当前应用根目录：{}".format(project_path) + "\n")
        return project_path
    except Exception as e:
        logger.append(traceback.format_exc())

